<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-充值审核 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;
use app\api\controller\EmailSend;
use think\facade\Db;

class FundCard extends Common
{
    //---------------------------------------------后端---------------------------------------------------------------
    /**
     * @param $post
     * @param $type
     * @return array
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['user_name']) && !empty($post['user_name'])){
            $where[] = ['username', 'like', '%'.$post['user_name'].'%'];
        }
        if(isset($post['value']) && !empty($post['value'])){
            $where[] = ['fc.value', 'like', '%'.$post['value'].'%'];
        }
        if(isset($post['amount']) && !empty($post['amount'])){
            $where[] = ['fc.amount', 'like', trim($post['amount'])];
        }
        if(isset($post['is_used']) && strlen($post['is_used']) >0){
            $where[] = ['fc.is_used', '=', trim($post['is_used'])];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['fc.ctime', 'between', "{$start_time},{$end_time}"];
        }
        $list = Db::name('fund_card')->alias('fc')
            ->leftJoin('user u','u.id=fc.user_id')
            ->field('u.username,fc.*')
            ->order('fc.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }
    public function fundEdit($data)
    {
        $blog           = true;
        $fc_id          = $data['fc_id'];
        $remark         = $data['remark'];
        $manage_remark  = $data['manage_remark'];
        $amount         = $data['amount']; //当前变更金额
        $check_status   = $data['check_status'];
        $manage_id      = $data['manage_id'];
        //获取审核表的信息
        $fc_list        = Db::name('fund_check')->find($fc_id);
        $user_id        = $fc_list['user_id'];
        $fc_amount      = $fc_list['amount'];
        $desc           = $fc_list['desc'];
        $check_num      = $fc_list['check_num'];
        $pay_type       = $fc_list['pay_type'];

        //获取对应用户余额
        $user_list      = Db::name('user')->find($user_id);
        $username       = $user_list['username'];
        $user_balance   = $user_list['balance'];


        Db::startTrans();
        try{
            $utime      = getUtcTime();
            $update_fund_check_data = [
                'check_status'  => $check_status,
                'remark'        => $remark,
                'msg'           => $manage_remark,
                'utime'         => $utime,
            ];
            if($check_status == 1){ //审核成功后
                //最终存储的余额,如果充值金额进行了修改，那么对修改的金额进行操作
                if(($fc_amount - $amount) != 0){
                    $fc_amount  = $amount;
                    //变更审核表中已修改的充值金额
                    $update_fund_check_data += ['amount' => $fc_amount];
                    $table_name = '';
                    $update    = '';
                    switch ($pay_type){
                        case 1:
                            $table_name = 'fund_check_alipay';
                            $update     = ['amount' => $amount];
                            break;
                        case 2:
                            $table_name = 'fund_check_wechat';
                            $update     = ['amount' => $amount];
                            break;
                    }
                    if(!empty($table_name)){
                        Db::name($table_name)->where(['check_num' =>$check_num])->update($update);
                    }
                }
                $end_balance    = $fc_amount + $user_balance;

                $update_fund_check_data += ['balance' => $end_balance];
                //更新用户余额
                Db::name('user')->where(['id'=>$user_id])
                    ->update(['balance' => $end_balance]);
                //记录钱包日志
                Db::name('user_cash_log')->save([
                    'user_id'       => $user_id,
                    'type'          => 0,   //0=Credit|1=Debit
                    'action_type'   => 1,   //1=充值
                    'amount'        => $fc_amount,
                    'balance'       => $end_balance,
                    'desc'          => $desc,
                    'ctime'         => $utime
                ]);
            }
            //发送邮件通知用户
            EmailSend::sendEmail('user_fund_check' , [
                'email'     => $username,
                'desc'      => "Dear member :{$username}, your recharge ($ {$fc_amount}), " . (($check_status == 1)? "approved successfully" : "audit failed")
            ]);
            //更新充值审核表
            Db::name('fund_check')->where(['id'=>$fc_id])
                ->update($update_fund_check_data);
            //记录操作日志
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => $desc,
                'time'      => $utime,
                'content'   => json_encode([
                    'check_status' => ($check_status == 1) ? 'success' : 'error',
                    'amount' => $fc_amount
                ])
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }
}